Skip to content

Remove allocations of nested Jacobians of StaticArrays#810

Open
albert-de-montserrat wants to merge 5 commits into
JuliaDiff:masterfrom
albert-de-montserrat:adm/nested_J
Open

Remove allocations of nested Jacobians of StaticArrays#810
albert-de-montserrat wants to merge 5 commits into
JuliaDiff:masterfrom
albert-de-montserrat:adm/nested_J

Conversation

@albert-de-montserrat
Copy link
Copy Markdown

Addresses and fixes the issue raised in #798.

The same MWE now yields:

using ForwardDiff, StaticArrays, Chairmarks

@inline f(x) = SVector(x[1]^2 * x[2], sin(x[1]) + x[2]^3)

function J_flat(x) 
    y = ForwardDiff.jacobian(f, x)
    SA[y[1], y[2]]
end

function nested_jacobian(x0::SVector{2, T}) where T
    ForwardDiff.jacobian(J_flat, x0)
end

x0 = SVector(1.0, 2.0)
julia> @b nested_jacobian($x0)
19.031 ns

Looks like the compiler was giving up to inline static_dual_eval(T, f, x) in this case. Manual inlining seems to solve the problem.

Refactor gradient and jacobian functions to use direct function calls instead of static_dual_eval.
@codecov
Copy link
Copy Markdown

codecov Bot commented May 31, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 87.75%. Comparing base (39916da) to head (bfc994e).

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #810      +/-   ##
==========================================
- Coverage   90.75%   87.75%   -3.01%     
==========================================
  Files          11       10       -1     
  Lines        1071      988      -83     
==========================================
- Hits          972      867     -105     
- Misses         99      121      +22     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Copy Markdown
Member

@devmotion devmotion left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a test that fails on master but passes with these changes?

@albert-de-montserrat
Copy link
Copy Markdown
Author

Added the following test, fails on master.

Comment thread test/AllocationsTest.jl Outdated
albert-de-montserrat and others added 2 commits June 4, 2026 16:44
Co-authored-by: David Müller-Widmann <devmotion@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants